<template>
  <div class="container" :class="{'darkmode' : isDarkmode}">
    <div class="top">
      <div class="top-left">
        <!-- 这里是天气小部件将被插入的地方 -->
        <div id="tp-weather-widget"></div>
      </div>
      <div class="top-right">
        <div class="top-right-darkmode" @click="changeDarkmode">
          <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#1f1f1f"><path d="M480-120q-150 0-255-105T120-480q0-150 105-255t255-105q14 0 27.5 1t26.5 3q-41 29-65.5 75.5T444-660q0 90 63 153t153 63q55 0 101-24.5t75-65.5q2 13 3 26.5t1 27.5q0 150-105 255T480-120Z"/></svg>
          <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#1f1f1f"><path d="M480-280q-83 0-141.5-58.5T280-480q0-83 58.5-141.5T480-680q83 0 141.5 58.5T680-480q0 83-58.5 141.5T480-280ZM200-440H40v-80h160v80Zm720 0H760v-80h160v80ZM440-760v-160h80v160h-80Zm0 720v-160h80v160h-80ZM256-650l-101-97 57-59 96 100-52 56Zm492 496-97-101 53-55 101 97-57 59Zm-98-550 97-101 59 57-100 96-56-52ZM154-212l101-97 55 53-97 101-59-57Z"/></svg>
        </div>
        <div class="top-right-person" @click="clickPersonalCenterEvent">
          <img :src="avatar" alt="头像">
          <span class="nickname">{{ nickname }}</span>
        </div>
      </div>
    </div>
    <div class="centre">
      <div class="centre-logo">
        <img src="../assets/images/logo.png" alt="Logo">
      </div>
      <div class="centre-search">
        <div class="centre-search-input">
          <!--             
            加了 :popper-append-to-body="false" 属性之后还是给我搞到了body里面去了
            所以直接就在base.css全局样式中设置高亮了
          -->
          <el-autocomplete
            popper-class="my-autocomplete"
            v-model="searchQuery"
            :fetch-suggestions="querySearch"
            placeholder="请输入你需要搜索的内容"
            clearable
            @select="handleSelect"
          >
            <template #default="{ item }">
              <span v-html="item.value"></span>
            </template>
          </el-autocomplete>
        </div>
        <!-- 点击事件放在div点击哪里都可以跳转 -->
        <div class="centre-search-icon" @click="clickSearchEvent">
          <el-icon style="height: 100%; width: 100%"><Search /></el-icon>
        </div>
      </div>
    </div>
    <div class="bottom">
      备案说明，xxx说明
    </div>

    <LoginDialog v-model="loginDialogVisible" @close-dialog="closeDialog"></LoginDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'; // 从Vue中导入ref函数用于响应式数据
import { ElAutocomplete, ElMessage } from 'element-plus'; // 从Element Plus中导入Autocomplete组件（虽然组件已经在模板中使用，但导入语句通常放在这里）
import {useRouter} from 'vue-router'
import LoginDialog from './components/LoginDialog.vue';
import {searchEngineApi} from '@/api/searchEngine.js'
import {historyApi} from '@/api/history.js'
import {settingApi} from '@/api/setting.js'

//### 变量定义 ###
const nickname = ref('游客');
const avatar = ref('http://8.130.118.52:9000/images/headPortrait/defaultHead.png'); //默认头像地址
const router = useRouter();
const isDarkmode = ref(false); //是否开启夜间模式

//用于存储历史记录
const history = ref<string[]>([]);

const searchRecord = ref([
  '把大象放进冰箱需要几步？',
  'Java是世界上最好的语言',
  'Python是世界上最好的语言',
  'js是世界上最好的语言',
  // 更多数据...
]);
 
const searchQuery = ref('');  //对应搜索框中的数据

const loginDialogVisible = ref(false);  //用户控制登录弹窗是否显示

//### 方法定义 ###
//控制夜间模式
const changeDarkmode = async () => {
  const darkMode= await settingApi.getSettingContentIsOpenByName({"name":"持久化夜间模式"});
  if(darkMode.code === 200 && darkMode.data) {
    ElMessage({
      message: '请先前往设置关闭对应用户的持久化夜间模式设置',
      type: 'warning',
    })
    return;
  }else {
    isDarkmode.value = !isDarkmode.value;
    window.localStorage.setItem('tenSeekIsDarkmode', isDarkmode.value + '');  //存储夜间模式到本地
  }
}

//搜索选中事件
const handleSelect = (selectItem:any) => {
  console.log("让我看看你选了", selectItem) //小心这里拿到的是ref
  const selectedValue = selectItem.value.replace(/<[^>]+>/g, ''); //移除对应html标签
  searchQuery.value = selectedValue;
}

//搜索提示词
const querySearch = async (queryString:any, cb:any) => {
  let results = null;
  if(queryString === '') {
    results = history.value.map(item => ({ value: item }));  //表示搜索框中的数据为空时，搜索提示历史数据
  }else {
    const data = await searchEngineApi.searchPrompt({suffix:queryString});
    if(data.code === 200) {
      console.log(data.data.complementList)
      const autocompleteData = data.data.complementList.map(item => ({ value: item }));
      results = autocompleteData;
    }else {
      results = searchRecord.value.map(item => ({ value: item }));
    }
  }

  cb(results);     // 使用回调函数返回搜索结果
};

function clickPersonalCenterEvent() {
  let token = window.localStorage.getItem("ten-seek-jwt")
  if(token) {
    router.push({
      name: 'collect'
    });
  }else {
    loginDialogVisible.value = true;
  }
}

const clickSearchEvent = () => {
  if(!searchQuery.value) {
    ElMessage({
      message: '搜索内容请不要为空哦！',
      type: 'warning',
    })
    return;
  }
  //获取搜索字段
  router.push({ name: 'searchResult', query: { query: searchQuery.value }});
}

function closeDialog() {
	loginDialogVisible.value = false;
}

//## 自定义事件方法
onMounted(async () => {
  (function(a,h,g,f,e,d,c,b){
    b=function(){
      d=h.createElement(g);
      c=h.getElementsByTagName(g)[0];
      d.src=e;
      d.charset="utf-8";
      d.async=1;
      c.parentNode.insertBefore(d,c)
    };
    a["SeniverseWeatherWidgetObject"]=f;
    a[f]||(a[f]=function(){
        (a[f].q=a[f].q||[]).push(arguments)
    });
    a[f].l=+new Date();
    if(a.attachEvent){
      a.attachEvent("onload",b)
    } else {
      a.addEventListener("load",b,false)
    }
  })(window,document,"script","SeniverseWeatherWidget",
    "//cdn.sencdn.com/widget2/static/js/bundle.js?t="+parseInt((new Date().getTime() / 100000000).toString(),10));

  // 确保脚本加载完成后尝试初始化天气插件
  const initializeWeatherWidget = () => {
    if (typeof window.SeniverseWeatherWidget === 'function') {
      window.SeniverseWeatherWidget('show', {
        flavor: "bubble",
        location: "WMHYTMYUZEVU",
        geolocation: true,
        language: "zh-Hans",
        unit: "c",
        theme: "auto",
        token: "05649c47-6be6-45bf-b15d-9a68c7bf3f54",
        hover: "enabled",
        container: "tp-weather-widget"
      });
    } else {
      console.error('SeniverseWeatherWidget is not a function. Ensure the script is correctly loaded.');
    }
  };

  // 延迟调用以确保外部脚本已加载
  setTimeout(initializeWeatherWidget, 1000); // 可根据实际情况调整延迟时间

  //夜间初始化部分
  let darkmode = window.localStorage.getItem('tenSeekIsDarkmode');
  if(darkmode === 'true') {
    isDarkmode.value = true;
  }

  //初始化昵称头像
  const name =  window.localStorage.getItem('ten-seek-nickname')
  if(name)  {
    nickname.value = name;
  }
  const head = window.localStorage.getItem('ten-seek-avatar')
  if(head) {
    avatar.value = head;
  }

  const darkMode= await settingApi.getSettingContentIsOpenByName({"name":"持久化夜间模式"});
  console.log('获取设置状态', darkMode)
  if(darkMode.code === 200) {
    if(darkMode.data) {
      isDarkmode.value = darkMode.data;
      window.localStorage.setItem('tenSeekIsDarkmode', isDarkmode.value + ''); 
    }
  }

  //初始化历史记录
  const result = await historyApi.obtainTheHistoricalRecordsTo5ThroughTheUserId();
  if(result.code === 200) {
    history.value = result.data.titles;
  }
});
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: hidden;
  background: var(--base-color);
  color: var(--text-color);

  .top{
    width: 100vw;
    flex: 0.1;
    // background: green;

    display: flex;
    flex-direction: row; /* 保持主轴为水平方向 */
    justify-content: space-between; /* 使子项在主轴上两端分布 */

    .top-left {
      // background: blue;
      margin-left: 20px;
    }

    .top-right {
      // background: blue;
      display: flex;
      align-items: center;  /* 复轴居中对齐 */

      .top-right-darkmode {
        margin-right: 20px;
        height: 30px;
        width: 30px;
        padding: 0;
        border-style: solid;
        border-radius: 50%;
        border-color: var(--border-color);
        background-color: var(--base-color);
        display: flex;
        justify-content: center;
        align-items: center;
      }

      /* 非暗模式下隐藏太阳 */
      .top-right-darkmode svg {
        fill: var(--primary-color);
      }

      .top-right-darkmode svg:last-child {
        display: none;
      }
      /* 非暗模式下隐藏太阳 */

      .top-right-person {
        margin-right: 20px;
        display: flex;
        align-items: center;

        img {
          border-radius: 50%;
          width: 50px;       /* 固定宽度 */
          height: 50px;      /* 固定高度，与宽度相同 */
          object-fit: cover; /* 保证图片比例不变形 */
          margin-right: 10px;
          display: block;    /* 避免行内元素的间隙问题 */
        }

        .nickname {
        }
      }
    }
  }

  .centre {
    width: 100vw;
    flex: 0.9;
    // background: red;
    
    .centre-logo {
      margin: auto;
      width: 933px;
      height: 300px;
      // background: blanchedalmond;

      display: flex;
      justify-content: center; /* 水平居中 */
      align-items: center; /* 垂直居中 */
    }

    .centre-search {
      margin: auto;
      width: 933px;
      height: 42px;

      text-align: center;
      display: flex;
      align-items: center;

      .centre-search-input {
        flex: 0.92;
        height: 100%;

        /* 深度样式控制，通过f12工具找到对应的名字进行样式设置 */
        ::v-deep .el-input__wrapper {
          border-top-left-radius: 10px; 
          border-bottom-left-radius: 10px; 
          border-top-right-radius: 0px; 
          border-bottom-right-radius: 0px;
          height: 42px; /* 要和对应centre-search高度一致 */
          background: var(--base-color);
        }

        /* 输入框内文字的颜色 */
        ::v-deep .el-input__inner {
          color: var(--text-color);
        }

        ::v-deep .el-scrollbar__wrap {
          background: black;
        }
      }

      .centre-search-icon {
        background: #409EFF;
        flex: 0.08;
        height: 100%;
        border-top-left-radius: 0px;
        border-bottom-left-radius: 0px;
        border-top-right-radius: 10px;
        border-bottom-right-radius: 10px;
      }
    }
  }

  .bottom {
    width: 100vw;
    flex: 0.05;
    text-align: center;
  }
}

/* 暗模式隐藏月亮 */
.darkmode .top .top-right .top-right-darkmode svg:first-child {
  display: none;
}

.darkmode .top .top-right .top-right-darkmode svg:last-child {
  display: block;
}
/* 暗模式隐藏月亮 */
</style>
